package com.shen.library_nettysocket.handler


import com.shen.library_nettysocket.netty.NettyTcpClient
import com.shen.library_nettysocket.protobuf.MessageProtobuf
import io.netty.channel.Channel
import io.netty.channel.ChannelInitializer
import io.netty.channel.ChannelPipeline
import io.netty.handler.codec.LengthFieldBasedFrameDecoder
import io.netty.handler.codec.LengthFieldPrepender
import io.netty.handler.codec.protobuf.ProtobufDecoder
import io.netty.handler.codec.protobuf.ProtobufEncoder
import java.lang.Exception

/**
 * Channel初始化配置
 */
class TCPChannelInitializerHandler(private val imsClient: NettyTcpClient) : ChannelInitializer<Channel?>() {

    @Throws(Exception::class)
    override fun initChannel(channel: Channel?) {
        val pipeline: ChannelPipeline? = channel?.pipeline()?.apply {

            // netty提供的「自定义长度·解码器」，解决「TCP拆包/粘包」问题
            addLast("frameEncoder", LengthFieldPrepender(2))
            addLast("frameDecoder", LengthFieldBasedFrameDecoder(
                65535, 0, 2, 0, 2))

            // 增加「protobuf编解码」支持
            addLast(ProtobufEncoder())
            addLast(ProtobufDecoder(MessageProtobuf.Msg.getDefaultInstance()))

            // 「握手认证消息」响应处理handler
            addLast(LoginAuthRespHandler::class.java.getSimpleName(), LoginAuthRespHandler(imsClient))
            // 「心跳消息」响应处理handler
            addLast(HeartbeatRespHandler::class.java.simpleName, HeartbeatRespHandler(imsClient))
            // 「接收消息」处理handler
            addLast(TCPReadHandler::class.java.simpleName, TCPReadHandler(imsClient))
        }
    }
}